import {pool} from "../base/Pool";
import {paserUiMiddleware} from "./middleware/paserUiMiddleware";
import AssetsBundle from "./AssetsBundle";
import AssetsBundleEvent from "./AssetsBundleEvent";
import {loadAssetBundle} from "./index";

export function loadAssets(assets, onProgress, onSuccess) {
    if (assets && assets.length > 0) {
        let bundle = pool.getItemByClass('AssetsBundle', AssetsBundle);
        bundle.addEventListener(
            AssetsBundleEvent.PROGRESS,
            (e) => {
                if (onProgress) {
                    onProgress(e.data.progress);
                }
            },
            this
        );
        bundle.addEventListener(
            AssetsBundleEvent.COMPLETE,
            (e) => {
                bundle.removeAllEventListener();
                bundle.dispose();
                pool.recover('AssetsBundle', bundle);
                if (onSuccess) {
                    onSuccess(e.data);
                }
            },
            this
        );
        bundle.setAfterMiddleware(paserUiMiddleware);
        assets.map(item => {
            bundle.add(item.name, item.url, item.options);
        });
        loadAssetBundle(bundle);

    } else {
        if (onSuccess) {
            onSuccess(null);
        }
    }
}